package com.xxl.job.executor.protocol;

import com.xxl.job.core.log.XxlJobLogger;

import java.io.IOException;
import java.net.*;

public class UDPProtocol {

    private DatagramSocket socket;
    private int port;
    private byte[] bytes;
    private DatagramPacket packet;

    public UDPProtocol(){

    }
    public UDPProtocol(int port){
        this.port=port;
        this.bytes=new byte[1024];//创建字节数组，指定接收的数据包的大小
        this.packet=new DatagramPacket(bytes, 30);//创建数据报
    }


    public boolean start() {
        try {
            socket=new DatagramSocket(port);
            XxlJobLogger.log("创建 <" + port + " UDPProtocol> 成功，等待接收数据 " );
            return true;
        } catch (SocketException e) {
            e.printStackTrace();
            XxlJobLogger.log("创建 <" + port + " UDPProtocol> 失败!!!  " + e.getMessage());
            return false;
        }
    }

    public boolean isAlived(){
        return socket.isClosed();
    }

    public byte[] receiveData(){
        try {
            //接收客户端发送的数据
            socket.receive(packet);//此方法在接收到数据报之前会一直阻塞
            //读取数据
            byte[] bytes = packet.getData();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
            XxlJobLogger.log("UDPProtocol接收数据异常---》"+e.getMessage());
            return null;
        }
    }


    public boolean sendData(byte[] sendData){

        InetAddress address = packet.getAddress();
        int clientPort = packet.getPort();

        //创建数据报，包含响应的数据信息
        DatagramPacket packetSend = new DatagramPacket(sendData, sendData.length, address, clientPort);
        //响应客户端
        try {
            socket.send(packetSend);
            XxlJobLogger.log("UDPProtocol发送数据成功，发送内容---》"+sendData);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            XxlJobLogger.log("UDPProtocol发送数据异常---》"+e.getMessage());
            return false;
        }

    }

    public boolean sendData(byte[] sendData, String ipAddress, String ipPort){

        InetAddress address = null;
        try {
            address = InetAddress.getByName(ipAddress);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        int clientPort = Integer.parseInt(ipPort);

        //创建数据报，包含响应的数据信息
        DatagramPacket packetSend = new DatagramPacket(sendData, sendData.length, address, clientPort);
        //响应客户端
        try {
            socket.send(packetSend);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            XxlJobLogger.log("UDPProtocol发送数据异常---》"+e.getMessage());
            return false;
        }

    }


}
